package com.adjy.pathbuilders.objects;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.contacts.Contact;

import com.adjy.pathbuilders.physics.MovementType;
import com.adjy.pathbuilders.physics.PhysicalObject;
import com.adjy.pathbuilders.rendering.AnimationPack;
import com.adjy.pathbuilders.sounds.SoundManager;
import com.adjy.pathbuilders.world.GameEntity;
import com.adjy.pathbuilders.world.GameWorld;
import com.adjy.pathbuilders.world.MainChar;

/**
 * Apple class implements a GameEntity Apple<br>
 * This Entity attracts the player for a certain amount of seconds if he is
 * close to it
 */
public class Apple extends GameEntity implements Thinkable {
	
	public final static float[] SIZE = {5, 5};

	private final static long SECONDS_TO_STOP = 5;

	private MovementType firstPlayerMovement = null;
	private long firstTimeStopped = -1;
	private boolean isColliding = false;
	private MainChar player;

	/**
	 * Creates an Apple
	 * 
	 * @param x
	 *            X Position
	 * @param y
	 *            Y Position
	 * @param frame
	 *            Frame to be used for rendering
	 */
	public Apple(float x, float y, AnimationPack ap) {
		super(GameEntityType.APPLE, x, y, SIZE[0], SIZE[1], ap, false, false, false);
		setAnimation("apple");
	}

	@Override
	public void hasStartedCollidingWith(PhysicalObject pObject, Contact contact) {
		if (pObject == null)
			return;
		
		if (((GameEntity) pObject).getType() == GameEntityType.MAINCHAR) {
			MainChar c = (MainChar) pObject;
			isColliding = true;
			player = c;

			if (firstPlayerMovement == null) {// Initial Contact
				SoundManager.getInstance().playSoundEffect("apple");
				firstPlayerMovement = c.getMovementType();
				if(firstPlayerMovement.equals(MovementType.STOPPED)) firstPlayerMovement = c.getLastMovementType();
			}
		}
	}

	@Override
	public void think(GameWorld gameWorld, float timePassed) {
		
		if (!isColliding)
			return;
		
		Vec2 pos = getBody().getPosition();
		
		// Follow Apple
		double appleCenterX = pos.x + (getWidth() / 2);
		double playerCenterX = player.getBody().getPosition().x + (player.getWidth() / 2);
		double xDiff = appleCenterX - playerCenterX;

		if (xDiff >= 5 || xDiff <= -5) { // Far Away -> Follow Apple
			if (xDiff > 0) {
				player.setMovementType(MovementType.MOVING_RIGHT);
			} else {
				player.setMovementType(MovementType.MOVING_LEFT);
			}
		} else { // Close -> Stop
			if (firstTimeStopped == -1)
				firstTimeStopped = System.currentTimeMillis();

			if (System.currentTimeMillis() - firstTimeStopped > SECONDS_TO_STOP * 1000) { // Expired
				kill();
				player.setMovementType(firstPlayerMovement);
				isColliding = false;
			} else { // Not Expired...
				player.setMovementType(MovementType.STOPPED);
			}
		}
	}
	
}
